using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QLHXNK.BusinessLogic;

namespace QLHXNK.Forms
{
    public partial class NewFrmNhapChiPhiHangThang : Form
    {
        int action = -1;
        private MonthlyExpenses monthlyExpenses;
        private MonthlyExpenses[] arrMonthlyExpensesExist = new MonthlyExpenses[100];
        private MonthlyExpenses[] arrMonthlyExpensesDeleted = new MonthlyExpenses[100];
        private int MonthlyExpensesExistCount = 0;
        private int MonthlyExpensesDeletedCount = 0;
        private bool isDeleteRow = false;
        private bool flagAction = true;

        private int[] arrayDeletedMonthName =new int[100];
        private int[] arrayDeletedYearName = new int[100];
        private int DeletedMonthNameCount = 0;

        public NewFrmNhapChiPhiHangThang()
        {
            InitializeComponent();
            this.CenterToScreen();
            MaChiPhi.DataSource = Expenses.ListExpenses();
            MaChiPhi.DisplayMember = "expenses_code";
        }

        private void NewFrmNhapChiPhiHangThang_Load(object sender, EventArgs e)
        {
            DataTable dtMonthlyExpenses = MonthlyExpenses.ListMonthlyExpenses();
            if (dtMonthlyExpenses.Rows.Count == 0)
            {
                DataTable dtExpenses = Expenses.ListExpenses();
                if (dtExpenses.Rows.Count == 0)
                {
                    MessageBox.Show("Bạn chưa có chi phí nào trong danh mục chi phí, bạn nên quay lại danh mục chí phí");
                    NewFrmDanhMucChiPhi frmDanhMucChiPhi = new NewFrmDanhMucChiPhi();
                    frmDanhMucChiPhi.ShowDialog();
                    this.Close();
                    return;
                }
            }
            
            dgvDanhSachChiPhi.DataSource = dtMonthlyExpenses;
            for (int i = 0; i < dtMonthlyExpenses.Rows.Count; i++)
            {
                String strThangtmp = dgvDanhSachChiPhi.Rows[i].Cells["ThangA"].Value.ToString();
                if (strThangtmp.Length == 1)
                    strThangtmp = "0"+dgvDanhSachChiPhi.Rows[i].Cells["ThangA"].Value.ToString();
                dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value=strThangtmp;
                dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value = dgvDanhSachChiPhi.Rows[i].Cells["NamA"].Value.ToString();
                dgvDanhSachChiPhi.Rows[i].Cells["SoTien"].Value = dgvDanhSachChiPhi.Rows[i].Cells["SoTienA"].Value;
            }
        }


        #region ---------------------------------sự kiện trên Form Danh sách chi phí-------------------------------

        private void dgvDanhSachChiPhi_SelectionChanged(object sender, EventArgs e)
        {
            
            MonthlyExpensesExistCount = 0;
            DeletedMonthNameCount = 0;
            DataGridViewSelectedRowCollection rows = dgvDanhSachChiPhi.SelectedRows;
            if (rows.Count == 1)
            {
                DataGridViewRow row = rows[0];
                UpdateDataInRowByMonth(row.Cells["Thang"].Value, row.Cells["Nam"].Value);

                if (row.Cells["ThangA"].Value!=null && row.Cells["ThangA"].Value.ToString() != ""
                    && row.Cells["NamA"].Value!=null && row.Cells["NamA"].Value.ToString() != "")
                {
                    lbKetQua.Visible = false;
                    DeletedMonthNameCount=1;
                    arrayDeletedMonthName[0] = Int32.Parse(row.Cells["ThangA"].Value.ToString());
                    arrayDeletedYearName[0] = Int32.Parse(row.Cells["NamA"].Value.ToString());

                    String strThangChiPhi = row.Cells["ThangA"].Value.ToString();
                    if (strThangChiPhi.Length == 1)
                        strThangChiPhi = "0" + strThangChiPhi;
                    strThangChiPhi+= "/" + row.Cells["NamA"].Value.ToString();
                    txtThang.Text = strThangChiPhi;
                    txtTongSoTien.Text = row.Cells["SoTienA"].Value.ToString();

                    DataTable dtMonthlyExpensesOFMonth = MonthlyExpenses.GetMonthlyExpensesByMonth(Int32.Parse(row.Cells["ThangA"].Value.ToString()), Int32.Parse(row.Cells["NamA"].Value.ToString()));
                    dgvChiTietThang.DataSource = dtMonthlyExpensesOFMonth;

                    for (int i = 0; i < dtMonthlyExpensesOFMonth.Rows.Count; i++)
                    {
                        dgvChiTietThang.Rows[i].Cells["SoTienCPNhap"].Value = dgvChiTietThang.Rows[i].Cells["SoTienCP"].Value;
                        arrMonthlyExpensesExist[MonthlyExpensesExistCount] = new MonthlyExpenses(
                                                            Int32.Parse(dtMonthlyExpensesOFMonth.Rows[i]["me.ID"].ToString()),
                                                            Int32.Parse(dtMonthlyExpensesOFMonth.Rows[i]["month_name"].ToString()),
                                                            Int32.Parse(dtMonthlyExpensesOFMonth.Rows[i]["year_name"].ToString()),
                                                            Int32.Parse(dtMonthlyExpensesOFMonth.Rows[i]["e.ID"].ToString()),
                                                            float.Parse(dtMonthlyExpensesOFMonth.Rows[i]["amount"].ToString()),
                                                            dtMonthlyExpensesOFMonth.Rows[i]["remark"].ToString());
                        MonthlyExpensesExistCount++;
                    }
                }
                else
                {
                    txtThang.Text = "";
                    txtTongSoTien.Text = "";
                    DataTable dtMonthlyExpensesOFMonth = MonthlyExpenses.GetMonthlyExpensesByMonth(0,0);
                    dgvChiTietThang.DataSource = dtMonthlyExpensesOFMonth;
                    dgvChiTietThang.ReadOnly = true;
                }
            }
            else if (rows.Count > 1)
            {
                DeletedMonthNameCount = 0;
                for (int i = 0; i < rows.Count; i++)
                {
                    DataGridViewRow row = rows[i];
                    if (row.Cells["Thang"].Value != null && row.Cells["Thang"].Value.ToString() != ""
                        && row.Cells["Nam"].Value != null && row.Cells["Nam"].Value.ToString() != "")
                    {
                        arrayDeletedMonthName[DeletedMonthNameCount] = Int32.Parse(row.Cells["Thang"].Value.ToString());
                        arrayDeletedYearName[DeletedMonthNameCount] = Int32.Parse(row.Cells["Nam"].Value.ToString());
                        DeletedMonthNameCount++;
                    }
                }
                txtThang.Text = "";
                txtTongSoTien.Text = "";
                DataTable dtMonthlyExpensesOFMonth = MonthlyExpenses.GetMonthlyExpensesByMonth(0,0);
                dgvChiTietThang.DataSource = dtMonthlyExpensesOFMonth;
            }
        }

        private void dgvDanhSachChiPhi_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (flagAction==true&& dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Thang"].Value != null && dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Thang"].Value.ToString() != ""
                &&dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Nam"].Value != null && dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Nam"].Value.ToString() != "")
            {
                String strThang = (dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Thang"].Value.ToString());
                if (strThang.Length == 1)
                    strThang = "0" + strThang;
                String strNam = (dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Nam"].Value.ToString());
                for (int i = 0; i < dgvDanhSachChiPhi.Rows.Count; i++)
                {
                    if (i != e.RowIndex && dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value != null && strThang == dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value.ToString()
                                        && dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value != null && strNam == dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value.ToString())
                    {
                        MessageBox.Show("Trong danh sách chi phí đã có tháng này");
                        dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Thang"].Value = "";
                        dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Nam"].Value = "";
                        dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["SoTien"].Value = "";
                        dgvDanhSachChiPhi.AllowUserToAddRows = false;
                        dgvDanhSachChiPhi.ClearSelection();
                        return;
                    }

                }
                if (dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["ThangA"].Value == null || dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["ThangA"].Value.ToString() == "")
                {
                    MonthlyExpenses monthlyExpenses= MonthlyExpenses.CreateMonthlyExpenses(Int32.Parse(strThang),Int32.Parse(strNam),Int32.Parse(Expenses.ListExpenses().Rows[0]["ID"].ToString()), 0, "");
                    if (monthlyExpenses == null)
                        MessageBox.Show("Thêm không thành công, vui lòng thử lại");
                    else
                    {
                        dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["ThangA"].Value = dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Thang"].Value;
                        dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["NamA"].Value = dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["Nam"].Value;
                        ShowNote("Thêm thành công tháng: " + monthlyExpenses.MonthName + " năm: "+monthlyExpenses.YearName+"", Color.Blue);
                        action = -1;
                    }
                }
            }
        }

        private void dgvDanhSachChiPhi_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 2)
            {
                dgvDanhSachChiPhi.ReadOnly = true;
                return;
            }

            if (e.RowIndex != -1 && dgvDanhSachChiPhi.Rows[e.RowIndex].Cells["ThangA"].Value.ToString() == "")
                dgvDanhSachChiPhi.ReadOnly = false;
            else
                dgvDanhSachChiPhi.ReadOnly = true;
        }

        private void dgvDanhSachChiPhi_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1 && dgvDanhSachChiPhi.Rows[dgvDanhSachChiPhi.Rows.Count - 1].Cells["Thang"].Value != null && dgvDanhSachChiPhi.Rows[dgvDanhSachChiPhi.Rows.Count - 1].Cells["Thang"].Value.ToString() != "")
                dgvDanhSachChiPhi.AllowUserToAddRows = true;
        }

        private void dgvDanhSachChiPhi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 46 && DeletedMonthNameCount>0)
            {
                DialogResult result = DialogResult;
                if (DeletedMonthNameCount == 1)
                    result = MessageBox.Show("Bạn muốn xoá chi phí tháng này", "Xoá", MessageBoxButtons.YesNo);
                if (DeletedMonthNameCount > 1)
                    result = MessageBox.Show("Bạn muốn xoá danh sách chi phí tháng bạn chọn", "Xoá", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    for (int i = 0; i < DeletedMonthNameCount; i++)
                    {
                        if (arrayDeletedMonthName[i] != 0 && arrayDeletedYearName[i]!=0)
                            MonthlyExpenses.DeleteMonthlyExpensesByMonthName(arrayDeletedMonthName[i],arrayDeletedYearName[i]);
                    }
                    DeletedMonthNameCount = 0;
                    DataTable dtMonthlyExpenses = MonthlyExpenses.ListMonthlyExpenses();
                    flagAction = false;
                    dgvDanhSachChiPhi.DataSource = dtMonthlyExpenses;
                    flagAction = true;
                    for (int i = 0; i < dtMonthlyExpenses.Rows.Count; i++)
                    {
                        String strThangtmp = dgvDanhSachChiPhi.Rows[i].Cells["ThangA"].Value.ToString();
                        if (strThangtmp.Length == 1)
                            strThangtmp = "0" + dgvDanhSachChiPhi.Rows[i].Cells["ThangA"].Value.ToString();
                        dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value = strThangtmp;
                        dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value = dgvDanhSachChiPhi.Rows[i].Cells["NamA"].Value.ToString();
                        dgvDanhSachChiPhi.Rows[i].Cells["SoTien"].Value = dgvDanhSachChiPhi.Rows[i].Cells["SoTienA"].Value;
                    }
                    if (dgvDanhSachChiPhi.Rows.Count > 0 && dgvDanhSachChiPhi.Rows[dgvDanhSachChiPhi.Rows.Count - 1].Cells["Thang"].Value != null && dgvDanhSachChiPhi.Rows[dgvDanhSachChiPhi.Rows.Count - 1].Cells["Thang"].Value.ToString() != "")
                        dgvDanhSachChiPhi.AllowUserToAddRows = true;
                }
            }
            if (e.KeyValue == 27)
                this.Close();
        }

        #endregion


        #region ----------------------------------sự kiện trên Form chi tiết tháng---------------------------------

        private void dgvChiTietThang_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2 && e.RowIndex != -1 && dgvChiTietThang.Rows[e.RowIndex].Cells["MaChiPhi"].Value != null && dgvChiTietThang.Rows[e.RowIndex].Cells["MaChiPhi"].Value.ToString() != "")
            {
                DataTable dtExpenses = Expenses.GetExpensesByCode(dgvChiTietThang.Rows[e.RowIndex].Cells["MaChiPhi"].Value.ToString());
                if (dtExpenses.Rows.Count > 0)
                {
                    dgvChiTietThang.Rows[e.RowIndex].Cells["TenChiPhi"].Value = dtExpenses.Rows[0]["expenses_name"].ToString();
                    dgvChiTietThang.Rows[e.RowIndex].Cells["ExpensesID"].Value = dtExpenses.Rows[0]["ID"].ToString();
                }
                else
                {
                    dgvChiTietThang.Rows[e.RowIndex].Cells["TenChiPhi"].Value = "";
                    dgvChiTietThang.Rows[e.RowIndex].Cells["ExpensesID"].Value = "-1";
                }
            }
        }

        private void dgvChiTietThang_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                lbKetQua.Visible = false;
                if (dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value ==null || dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value.ToString() == "" || dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value.ToString() == "-1")
                    action = 0;
                else
                    action = 2;
            }
        }

        private void dgvChiTietThang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 46 && MonthlyExpensesDeletedCount > 0)
            {
                isDeleteRow = true;
                DialogResult result = DialogResult;
                if (MonthlyExpensesDeletedCount == 1)
                    result = MessageBox.Show("Bạn muốn xoá chi tiết này", "Xoá", MessageBoxButtons.YesNo);
                if (MonthlyExpensesDeletedCount > 1)
                    result = MessageBox.Show("Bạn muốn xoá danh sách chi tiết này", "Xoá", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    dgvChiTietThang.AllowUserToDeleteRows = true;
                    for (int i = 0; i < MonthlyExpensesDeletedCount; i++)
                    {
                        int kq = arrMonthlyExpensesDeleted[i].DeleteMonthlyExpenses();
                        if (kq == 1)
                        {
                            DeleteArrMonthlyExpensesExist(arrMonthlyExpensesDeleted[i].ID);
                            UpdateAmountOnForm();
                        }
                    }
                    MonthlyExpensesDeletedCount = 0;
                    txtTongSoTien.Text = SumExpenses().ToString();
                }
                else
                    dgvChiTietThang.AllowUserToDeleteRows = false;
            }
            if (e.KeyValue == 27)
                this.Close();
        }

        private void dgvChiTietThang_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            int monthName = 0;
            int yearName = 0;
            int expensesID = -1;
            double amount = 0;
            String remark = "";


            if (txtThang.Text != "")
            {
                monthName = Int32.Parse(txtThang.Text.Substring(0, 2));
                yearName = Int32.Parse(txtThang.Text.Substring(3));
            }
            if (dgvChiTietThang.Rows[e.RowIndex].Cells["GhiChu"].Value != null)
                remark = dgvChiTietThang.Rows[e.RowIndex].Cells["GhiChu"].Value.ToString().Trim();
            
            if (dgvChiTietThang.Rows[e.RowIndex].Cells["ExpensesID"].Value != null && dgvChiTietThang.Rows[e.RowIndex].Cells["ExpensesID"].Value.ToString() != "")
                expensesID = Int32.Parse(dgvChiTietThang.Rows[e.RowIndex].Cells["ExpensesID"].Value.ToString());

            if (e.RowIndex != -1 && action==0 )
            {
                if (expensesID != -1)
                {
                    try
                    {
                        amount = double.Parse(dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCPNhap"].Value.ToString());
                    }
                    catch
                    {
                        MessageBox.Show("Số tiền chi phí không hợp lệ");
                        action = -1;
                        return;
                    }
                    for (int j = 0; j < dgvChiTietThang.Rows.Count; j++)
                        if (j != e.RowIndex && dgvChiTietThang.Rows[j].Cells["ExpensesID"].Value != null && expensesID.ToString() == dgvChiTietThang.Rows[j].Cells["ExpensesID"].Value.ToString())
                        {
                            MessageBox.Show("Đã chi phí này trong tháng ");
                            ClearDataOnDGV(e.RowIndex);
                            action = -1;
                            return;
                        }
                    monthlyExpenses = MonthlyExpenses.CreateMonthlyExpenses(monthName,yearName,expensesID,amount,remark);

                    if (monthlyExpenses == null)
                        MessageBox.Show("Dữ liệu nhập vào không hơp hợp lệ ");
                    else
                    {
                        ShowNote("Thêm thành công chi tiết của tháng: " + monthlyExpenses.MonthName + " năm:"+monthlyExpenses.YearName+"", Color.Blue);
                        arrMonthlyExpensesExist[MonthlyExpensesExistCount++] = monthlyExpenses;
                        UpdateAmountOnForm();

                    }
                    action = -1;
                }
                else
                {
                    MessageBox.Show("Bạn hảy nhập đầy đủ thông tin cho chi phí");
                    ClearDataOnDGV(e.RowIndex);
                    action = -1;
                    return;
                }
            }

            if (e.RowIndex != -1 && action == 2)
            {
                try
                {
                    amount = double.Parse(dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCPNhap"].Value.ToString());
                }
                catch
                {
                    MessageBox.Show("Số tiền chi phí không hợp lệ, nên không thể cập nhật thông tin");
                    dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCPNhap"].Value = dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCP"].Value;
                    action = -1;
                    return;
                }
                int i;
                for (i = 0; i < MonthlyExpensesExistCount; i++)
                {
                    if (arrMonthlyExpensesExist[i].ID.ToString() == dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value.ToString())
                        break;
                }
                if (expensesID != -1)
                {
                    for (int j = 0; j < dgvChiTietThang.Rows.Count; j++)
                        if (j != e.RowIndex && dgvChiTietThang.Rows[j].Cells["ExpensesID"].Value != null && expensesID.ToString() == dgvChiTietThang.Rows[j].Cells["ExpensesID"].Value.ToString())
                        {
                            MessageBox.Show("Đã có chi phí nay trong tháng này");
                            RollbackDataOnDGV(i, e.RowIndex);
                            action = -1;
                            return;
                        }

                    try
                    {
                        int kq=arrMonthlyExpensesExist[i].UpdateMonthlyExpenses(expensesID,amount,remark);
                        if (kq == 1)
                        {
                            ShowNote("Đã cập nhập thông tin cho chi tiết của tháng " + arrMonthlyExpensesExist[i].MonthName + " năm:"+arrMonthlyExpensesExist[i].YearName+"", Color.Blue);
                            UpdateAmountOnForm();
                        }
                        action = -1;
                    }
                    catch { action = -1; }

                }
                else
                {
                    MessageBox.Show("Chưa cập nhật thông tin vì không đủ thông tin cho chi phí");
                    RollbackDataOnDGV(i,e.RowIndex);
                    action = -1;
                    return;
                }

            }
        }

        private void dgvChiTietThang_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (isDeleteRow == true)
            {
                isDeleteRow = false;
                DataTable dtMonthlyExpenses = MonthlyExpenses.GetMonthlyExpensesByMonth(int.Parse(txtThang.Text.Substring(0,2)),Int32.Parse(txtThang.Text.Substring(3)));
                dgvChiTietThang.DataSource = dtMonthlyExpenses;
                for(int i=0;i<dtMonthlyExpenses.Rows.Count;i++)
                    dgvChiTietThang.Rows[i].Cells["SoTienCPNhap"].Value = dgvChiTietThang.Rows[i].Cells["SoTienCP"].Value;
            }
            action = -1;
        }

        private void dgvChiTietThang_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rows = dgvChiTietThang.SelectedRows;
            if (rows.Count > 0)
            {
                MonthlyExpensesDeletedCount =0;
                for (int i = 0; i < rows.Count; i++)
                {
                    DataGridViewRow row = rows[i];
                    

                    if (row.Cells["MonthlyExpensesID"].Value != null && row.Cells["MonthlyExpensesID"].Value.ToString() != ""
                        && row.Cells["SoTienCPNhap"].Value != null && row.Cells["SoTienCPNhap"].Value.ToString() != "")
                    {
                        arrMonthlyExpensesDeleted[MonthlyExpensesDeletedCount++] = new MonthlyExpenses(Int32.Parse(row.Cells["MonthlyExpensesID"].Value.ToString()),
                                        Int32.Parse(row.Cells["MonthName"].Value.ToString()),
                                        Int32.Parse(row.Cells["YearName"].Value.ToString()),
                                        Int32.Parse(row.Cells["ExpensesID"].Value.ToString()),
                                        float.Parse(row.Cells["SoTienCP"].Value.ToString()),
                                        row.Cells["GhiChu"].Value.ToString());
                    }
                }

            }
        }

        private void dgvChiTietThang_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 3)
                dgvChiTietThang.ReadOnly = true;
            else
                if (txtThang.Text != "")
                {
                    dgvChiTietThang.ReadOnly = false;
                    dgvChiTietThang.Columns["TenChiPhi"].ReadOnly = true;
                }
        }

        #endregion


        #region ------------------------------------Hàm hổ trợ chức năng-------------------------------------------

        private void DeleteArrMonthlyExpensesExist(int ID)
        {
            int i;
            for (i = 0; i < MonthlyExpensesExistCount; i++)
            {
                if (ID == arrMonthlyExpensesExist[i].ID)
                {
                    MonthlyExpensesExistCount--;
                    break;
                }
            }
            for (int j = i; j < MonthlyExpensesExistCount; j++)
                arrMonthlyExpensesExist[j] = arrMonthlyExpensesExist[j + 1];

        }

        /// <summary>
        /// Tính tổng chi phí của tháng
        /// </summary>
        /// <returns></returns>
        private double SumExpenses()
        {
            double sum = 0;
            for (int i = 0; i < MonthlyExpensesExistCount; i++)
            {
                sum = sum + arrMonthlyExpensesExist[i].Amount;
            }
            return sum;
        }

        /// <summary>
        /// Cập nhật tổng chi phí cho tháng trên Form
        /// </summary>
        private void UpdateAmountOnForm()
        {
            txtTongSoTien.Text = SumExpenses().ToString();
            for (int i = 0; i < dgvDanhSachChiPhi.Rows.Count; i++)
            {
                if (dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value != null && dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value.ToString() != ""
                    &&dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value != null && dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value.ToString() != "")
                {
                    if (txtThang.Text.Substring(0,2) == dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value.ToString()
                        &&txtThang.Text.Substring(3) == dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value.ToString())
                    {
                        dgvDanhSachChiPhi.Rows[i].Cells["SoTien"].Value = txtTongSoTien.Text;
                        dgvDanhSachChiPhi.Rows[i].Cells["SoTienA"].Value = txtTongSoTien.Text;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Quay lại dữ liệu cũ tại dòng index
        /// </summary>
        /// <param name="i"></param>
        /// <param name="index"></param>
        private void RollbackDataOnDGV(int i, int index)
        {
            DataTable dtExpenses = Expenses.GetExpensesByID(arrMonthlyExpensesExist[i].ExpensesID);
            dgvChiTietThang.Rows[index].Cells["MaChiPhi"].Value = dtExpenses.Rows[0]["expenses_code"].ToString();
            dgvChiTietThang.Rows[index].Cells["TenChiPhi"].Value = dtExpenses.Rows[0]["expenses_name"].ToString();
            dgvChiTietThang.Rows[index].Cells["SoTienCPNhap"].Value = arrMonthlyExpensesExist[i].Amount;
            dgvChiTietThang.Rows[index].Cells["GhiChu"].Value = arrMonthlyExpensesExist[i].Remark;
        }

        /// <summary>
        /// Xoá dữ liệu trên DGV tai dòng index
        /// </summary>
        /// <param name="index"></param>
        private void ClearDataOnDGV(int index)
        {
            dgvChiTietThang.Rows[index].Cells["MaChiPhi"].Value = "";
            dgvChiTietThang.Rows[index].Cells["TenChiPhi"].Value = "";
            dgvChiTietThang.Rows[index].Cells["SoTienCPNhap"].Value = "";
            dgvChiTietThang.Rows[index].Cells["GhiChu"].Value = "";
        }

        private void UpdateDataInRowByMonth(Object monthName,Object yearName)
        {
            if (monthName == null)
                monthName = "";
            if (yearName == null)
                yearName = "";
            for (int i = 0; i < dgvDanhSachChiPhi.Rows.Count; i++)
            {
                if (dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value != null && dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value.ToString() != ""
                    && dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value != null && dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value.ToString() != "")
                    if (dgvDanhSachChiPhi.Rows[i].Cells["Thang"].Value.ToString() == monthName.ToString() && dgvDanhSachChiPhi.Rows[i].Cells["Nam"].Value.ToString() == yearName.ToString())
                        if (dgvDanhSachChiPhi.Rows[i].Cells["SoTienA"].Value==null || dgvDanhSachChiPhi.Rows[i].Cells["SoTienA"].Value.ToString()=="")
                        {
                            dgvDanhSachChiPhi.Rows[i].Cells["SoTien"].Value = SumExpenses();
                            dgvDanhSachChiPhi.Rows[i].Cells["SoTienA"].Value = dgvDanhSachChiPhi.Rows[i].Cells["SoTien"].Value;
                        }
            }
        }


        /// <summary>
        /// Hiển thị chú thích
        /// </summary>
        /// <param name="note"></param>
        /// <param name="foreColor"></param>
        private void ShowNote(string note, Color foreColor)
        {
            lbKetQua.Visible = true;
            lbKetQua.ForeColor = foreColor;
            lbKetQua.Text = note;
        }

        #endregion

        private void txtThang_KeyDown(object sender, KeyEventArgs e)
        {
            NewFrmNhapChiPhiHangThang_KeyDown(this, e);
        }

        private void txtTongSoTien_KeyDown(object sender, KeyEventArgs e)
        {
            NewFrmNhapChiPhiHangThang_KeyDown(this, e);
        }

        private void NewFrmNhapChiPhiHangThang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 27)
                this.Close();
        }

        private void dgvChiTietThang_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvChiTietThang.Rows[e.RowIndex].Cells["MaChiPhi"].Value != null && dgvChiTietThang.Rows[e.RowIndex].Cells["MaChiPhi"].Value.ToString() != ""
                && dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCPNhap"].Value != null && dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCPNhap"].Value.ToString() != ""
                && (dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value == null || dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value.ToString() == ""))
            {
                DataTable dtMonthlyExpensestmp = MonthlyExpenses.GetMonthlyExpensesByMonthAndExpexsesCode(Int32.Parse(txtThang.Text.Substring(0, 2)),
                                                Int32.Parse(txtThang.Text.Substring(3)), dgvChiTietThang.Rows[e.RowIndex].Cells["MaChiPhi"].Value.ToString());
                if (dtMonthlyExpensestmp.Rows.Count > 0)
                {
                    dgvChiTietThang.Rows[e.RowIndex].Cells["MonthlyExpensesID"].Value = Int32.Parse(dtMonthlyExpensestmp.Rows[0]["me.ID"].ToString());
                    dgvChiTietThang.Rows[e.RowIndex].Cells["MonthName"].Value = Int32.Parse(dtMonthlyExpensestmp.Rows[0]["month_name"].ToString());
                    dgvChiTietThang.Rows[e.RowIndex].Cells["YearName"].Value = Int32.Parse(dtMonthlyExpensestmp.Rows[0]["year_name"].ToString());
                    dgvChiTietThang.Rows[e.RowIndex].Cells["ExpensesID"].Value = Int32.Parse(dtMonthlyExpensestmp.Rows[0]["e.ID"].ToString());
                    dgvChiTietThang.Rows[e.RowIndex].Cells["SoTienCP"].Value = Int32.Parse(dtMonthlyExpensestmp.Rows[0]["amount"].ToString());
                    dgvChiTietThang.Rows[e.RowIndex].Cells["GhiChu"].Value = (dtMonthlyExpensestmp.Rows[0]["remark"].ToString());
                }
            }
        }

    }
}